// 防抖函数
function debounce(func, wait = 300) {
    let timeout;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}

// 单次监听器
import { watch } from 'vue';
let unwatchOnce = null;
const watchOnce = function (value, func) {
    unwatchOnce = watch(
        value,
        () => {
            func()
            unwatchOnce()
            unwatchOnce = null

        }
    )
}

// 序列化函数
const mapToJson = function (map) {
    const mapToArray = function (map) {
        let mapArray = Array.from(map.entries());
        mapArray = mapArray.map(
            ([key, value]) => {
                if (value instanceof Map) {
                    return [key, mapToArray(value)];
                }
                return [key, value];
            }
        )
        return mapArray;
    }
    const mapArray = mapToArray(map);
    const json = JSON.stringify(mapArray);
    return json;
}


const jsonToMap = function (json) {
    const mapArray = JSON.parse(json);

    const isMapArray = (array) => {
        // 自己是一个数组
        // 所有的子元素是一个length=2的数组
        return Array.isArray(array) && array.every(e => Array.isArray(e) && e.length == 2)
    }

    const mapArrayToMap = function (mapArray) {
        const map = new Map();

        if (isMapArray(mapArray)) {
            mapArray.map(
                ([key, value]) => {
                    if (isMapArray(value)) {
                        map.set(key, mapArrayToMap(value))
                    } else {
                        map.set(key, value)
                    }
                }
            )
        } else {
            throw new Error("该json并非是由map转化而成")
        }
        return map;
    }

    const map = mapArrayToMap(mapArray);
    console.log(map);
    return map;
}




export {
    debounce,
    watchOnce,
    mapToJson,
    jsonToMap,
};